package com.indusfo.spc.controller;

import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.RuleListService;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author chenm
 * @create 2019-07-23 14:17
 */
@RequestMapping("/ruleList")
@Controller
public class RuleListController {

    @Autowired
    private RuleListService ruleListService;

    /**
     * 新增
     */
    @RequestMapping("/insertRuleList")
    @ResponseBody
    public JSONObject insertRuleList(RuleList ruleList){
        JSONObject json = ruleListService.insertRuleList(ruleList);
        return json;
    }

    /**
     * 删除
     */
    @RequestMapping("/delRuleList")
    @ResponseBody
    public JSONObject delRuleList(Integer[] ids, Integer  dataState){
        dataState = 2;
        JSONObject json = ruleListService.delRuleList(ids,dataState);
        return json;
    }

    /**
     * 停用
     */
    @RequestMapping("/stopRuleList")
    @ResponseBody
    public JSONObject stopRuleList(Integer[] ids, Integer  dataState){
        dataState = 3;
        JSONObject json = ruleListService.delRuleList(ids,dataState);
        return json;
    }


    /**
     * 启用
     */
    @RequestMapping("/startRuleList")
    @ResponseBody
    public JSONObject startRuleList(Integer[] ids, Integer  dataState){
        dataState = 1;
        JSONObject json = ruleListService.delRuleList(ids,dataState);
        return json;
    }

    /**
     * 修改
     */
    @RequestMapping("updateRuleList")
    @ResponseBody
    public JSONObject updateRuleList(RuleList ruleList){
        JSONObject json = ruleListService.updateRuleList(ruleList);
        return json;
    }

    /**
     * 查询
     * @param ruleList
     * @return
     */
    @RequestMapping("/queryRuleList")
    @ResponseBody
    public JSONObject queryRuleList(RuleList ruleList){
        JSONObject json = ruleListService.queryRuleList(ruleList);
        return json;
    }
    @RequestMapping("/uploadFileRuleList")
    @ResponseBody
    public JSONObject uploadFileUser(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        //定义一个message对象用于向前台传输数据
        Message msg = new Message();
        //设置错误集合的
        List<ExcelErrorData> errorDatas = new ArrayList<>();
        response.setContentType("text/html;charset=UTF-8");
        //判断上传文件格式是否正确
        Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
        if (wb == null) {
            errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
        } else {
            //获取excel文件的第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                msg.setCode(2);
                msg.setMsg("未找到需要导入的表格");
                errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
            } else {
                //获取最后一行的行号
                int rowCount = sheet.getLastRowNum();
                if (rowCount < 1) {
                    msg.setCode(1);
                    msg.setMsg("未找到需要导入的数据，请确认表格是否保存！！！");
                    errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认表格是否保存！！！"));
                } else {
                    List<RuleList> addProductPlans = new ArrayList<>();
                    for (int i = 1; i <= rowCount; i++) {
                        boolean needAdd = true;
                        //获取到每一行的每一列的数据
                        //条码规则类别名称
                        String ruleName =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
                        //常量名称
                        String clName =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 1, false);
                        //类型名称
                        String type = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 2, false);
                        //格式
                        String form =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 3, false);
                        //初始值
                        String first =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 4, false);
                        //长度
                        String len = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 5, false);
                        //步长
                        String length = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 6, false);
                        //备注
                        String remark = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 7, false);
                        RuleList plan = new RuleList(ruleName,clName,first,type,form,len,length,remark);
                        int m = i + 1;
                        //将excel中的每一行数据存储进行检查
                        String result = ruleListService.checkNoRepeatExcel(plan);
                        if(result!=null){
                            errorDatas.add(ExcelErrorData.getExcelErrorData(i, result));
                            needAdd=false;
                        }

                        if (needAdd) {
                            addProductPlans.add(plan);
                        } else {
                            msg.setCode(2);
                            msg.setMsg("导入数据中存在异常信息");
                        }

                    }
                    //根据这些来判断是否是中止导入还是跳过继续进行导入
                    if (msg.getCode() == 2 && !way) {
                        msg.setMsg(msg.getMsg() + ",中止导入");
                    } else {
                        if (addProductPlans.size() > 0) {
                            try {
                                ruleListService.updateListRuleList(addProductPlans);
                                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                                msg.setMsg(StringUtils.isBlank(msg.getMsg()) ? "导入成功" : msg.getMsg());
                                if ("导入成功".equals(msg.getMsg())) {
                                    msg.setCode(1);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                msg.setMsg("导入失败");
                            }
                        }
                    }
                    //msg.setData(GsonUtil.toJson(errorDatas));
                }
            }
        }
        msg.setData(GsonUtil.toJson(errorDatas));
        //response.getWriter().println(GsonUtil.toJson(msg));
        String s = GsonUtil.toJson(msg);
        return JSONObject.build(200,msg.getMsg(),errorDatas);
    }

}
